//
//  Router.swift
//  CitySearch
//
//  Created by guotonglin on 2020/6/8.
//  Copyright © 2020 guotonglin. All rights reserved.
//

import Foundation
import UIKit

class Router: NSObject {
    
    private var navigateionConroller: UINavigationController
    private var closures: [String : NavigationBackClosure] = [:]
    
    init(navigateionConroller: UINavigationController) {
        self.navigateionConroller = navigateionConroller
        super.init()
        self.navigateionConroller.delegate = self
    }
}

extension Router: Routing {
    
    func push(_ drawable: Drawable, isAnimated: Bool, onNavigationBack closure: NavigationBackClosure?) {
        
        guard let viewController = drawable.viewController else {
            return
        }
        
        if let clusure = closure {
            closures.updateValue(clusure, forKey: viewController.description)
        }
        self.navigateionConroller.pushViewController(viewController, animated: isAnimated)
    }
    
    func pop(_ isAnimated: Bool) {
        self.navigateionConroller.popViewController(animated: isAnimated)
    }
    
    func popToRoot(_ isAnimated: Bool) {
        self.navigateionConroller.popToRootViewController(animated: isAnimated)
    }
    
    func present(_ drawable: Drawable, isAnimated: Bool, onDismiss closure: NavigationBackClosure?) {
        guard let viewController = drawable.viewController else {
            return
        }
        if let clusure = closure {
            closures.updateValue(clusure, forKey: viewController.description)
        }
        viewController.presentationController?.delegate = self
        self.navigateionConroller.present(viewController, animated: isAnimated, completion: nil)
    }
    
    func excureClosure(_ viewConroller: UIViewController) {
        guard let closure = closures.removeValue(forKey: viewConroller.description) else {
            return
        }
        closure()
    }
}

extension Router: UINavigationControllerDelegate {
    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
        guard let previousConroller = navigationController.transitionCoordinator?.viewController(forKey: .from) else {
            return
        }
        guard !navigationController.viewControllers.contains(previousConroller) else {
            return
        }
        self.excureClosure(previousConroller)
    }
}

extension Router: UIAdaptivePresentationControllerDelegate {
    func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
        self.excureClosure(presentationController.presentedViewController)
    }
}

